export const debounce = function (fun, immediate, duration = 1000) {
  // 防抖函数
  let timer = null
  return function () {
    const that = this
    const args = arguments
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
    if (immediate) {
      const callNow = !timer
      if (callNow) {
        fun.apply(that, args)
        timer = setTimeout(() => {
          timer = null
        }, duration)
      }
    } else {
      timer = setTimeout(() => {
        fun.apply(that, args)
      }, duration)
    }
  }
}

export const throttle = function (fn, duration = 1000) {
  // 节流函数
  let last
  let timer = null
  let now
  return function () {
    if (timer === null) {
      last = new Date().getTime()
      timer = setTimeout(() => {
        timer = null
        fn.call(this, ...arguments)
      }, duration)
    } else {
      now = new Date().getTime()
      if (now - last <= duration) {
        clearTimeout(timer)
        last = now
        timer = setTimeout(() => {
          timer = null
          fn.call(this, ...arguments)
        }, duration)
      }
    }
  }
}
